﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lruc.Model;
using Masuit.Tools.Security;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace lruc.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IFreeSql _fsql;
        public UserController(IFreeSql fsql){
            this._fsql = fsql;
        }

        [HttpPost]
        public async Task<Dictionary<string, Object>> Login([FromForm] User user) {
            User loginUser = await _fsql.Select<User>().Where(u => u.Username == user.Username && u.Password == user.Password).ToOneAsync();
            if (loginUser == null) {
                return RenderJson(status: "failed", message : "账号/密码错误", code: -1);
            }
            string token = DateTime.Now.ToString().MDString("lru");
            int affrows = await _fsql.Update<User>(loginUser.Id).Set(u => u.Token, token).ExecuteAffrowsAsync();
            loginUser.Token = token;
            return RenderJson(data: loginUser);
        }

        [NonAction]
        protected Dictionary<string, Object> RenderJson(string status = "success", string message = "成功", int code = 0, Object data = null)
        {
            Dictionary<string, Object> result = new Dictionary<string, object>();
            result.Add("status", status);
            result.Add("message", message);
            result.Add("code", code);
            result.Add("data", data);
            return result;
        }
    }
}
